/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.entity.Course;
import com.bishe.entity.Teacher;
import com.bishe.entity.User;
import com.bishe.entity.resp.CommonPageRequest;
import com.bishe.entity.resp.CommonSortOrderEnum;
import com.bishe.entity.resp.LoginInfo;
import com.bishe.entity.resp.UserInfo;
import com.bishe.exception.CommonException;
import com.bishe.mapper.UserMapper;
import com.bishe.param.UserAddParam;
import com.bishe.param.UserEditParam;
import com.bishe.param.UserIdParam;
import com.bishe.param.UserPageParam;
import com.bishe.service.CourseService;
import com.bishe.service.TeacherService;
import com.bishe.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * userService接口实现类
 *
 * @author null
 * @date 2024/03/11 16:15
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private TeacherService teacherService;

    @Resource
    private CourseService courseService;

    @Override
    public Page<User> page(UserPageParam userPageParam) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isAllNotEmpty(userPageParam.getSearchKey(), userPageParam.getSearchValue())){
            queryWrapper.eq(true,StrUtil.toUnderlineCase(userPageParam.getSearchKey()),userPageParam.getSearchValue());
        }

        if (ObjectUtil.isAllNotEmpty(userPageParam.getSortField(), userPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(userPageParam.getSortOrder());
            queryWrapper.orderBy(true, userPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(userPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(User::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(UserAddParam userAddParam) {
        User user = BeanUtil.toBean(userAddParam, User.class);
        this.save(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(UserEditParam userEditParam) {
        User user = this.queryEntity(userEditParam.getId());
        BeanUtil.copyProperties(userEditParam, user);
        this.updateById(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<UserIdParam> userIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(userIdParamList, UserIdParam::getId));
    }

    @Override
    public User detail(UserIdParam userIdParam) {
        return this.queryEntity(userIdParam.getId());
    }

    @Override
    public User queryEntity(String id) {
        User user = this.getById(id);
        if (ObjectUtil.isEmpty(user)) {
            throw new CommonException("user不存在，id值为：{}", id);
        }
        return user;
    }

    @Override
    public UserInfo login(LoginInfo loginInfo) {
        // 检查登录信息
        if (loginInfo == null) {
            throw new CommonException("登录失败!");
        }

        if (StrUtil.isEmpty(loginInfo.getUserName()) || StrUtil.isEmpty(loginInfo.getPassword())) {
            throw new CommonException("用户名密码为空!");
        }

        String userName = loginInfo.getUserName();
        String password = loginInfo.getPassword();

        UserInfo userInfo = new UserInfo();

        // 登录用户查询
        User one = getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, userName)
                .eq(User::getPwd, password), false);

        if (ObjectUtil.isNotEmpty(one)) {
            StpUtil.login(one.getId());

            userInfo.setId(one.getId());
            userInfo.setName(one.getUsername());
            userInfo.setToken(StpUtil.getTokenValue());
            userInfo.setType("admin".equals(userName) ? "admin" : "student");
            return userInfo;
        }

        Teacher teacher = teacherService.getOne(Wrappers.<Teacher>lambdaQuery()
                .eq(Teacher::getNumberNo, userName)
                .eq(Teacher::getPwd, password), true);

        if (ObjectUtil.isEmpty(teacher)){
            throw new CommonException("用户名密码错误!");
        }
        StpUtil.login(teacher.getId());
        userInfo.setId(teacher.getId());
        userInfo.setName(teacher.getNumberNo());
        userInfo.setToken(StpUtil.getTokenValue());
        userInfo.setType("teacher");
        return userInfo;

    }

    @Override
    public List<User> myStu() {
        StpUtil.checkLogin();
        // 教师id
        String teacherId = StpUtil.getLoginIdAsString();
        List<Course> courseList = courseService.list(Wrappers.lambdaQuery(Course.class).eq(Course::getTid, teacherId));

        List<String> uids = new ArrayList<>();
        for (Course course : courseList) {
            uids = Arrays.asList(course.getUid().split(","));
        }
        if (CollUtil.isEmpty(uids)){
            return  new ArrayList<>();
        }
        return listByIds(uids);
    }

}
